package com.yxplearn.mybatisplus.match;

import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.LinkedBlockingQueue;

@Component
public class MatchQueueManager {

    private static final Map<Integer, Player> playerMap = new HashMap<Integer, Player>();
    private static final Queue<Player> matchQueue = new ConcurrentLinkedDeque<>();
    private static final Queue<MatchResult> matchResults = new ConcurrentLinkedDeque<>();

    public static boolean addQueue(Player player) {
        playerMap.put(player.getId(), player);
        return matchQueue.add(player);
    }

//    public MatchResult match0() {
//        MatchResult matchResult = new MatchResult();
//        matchResult.setState(0);
//        if (!matchQueue.isEmpty()) {
//            matchResult.setState(1);
//        }
//        if (matchQueue.size() >= 8) {
//            Queue<Player> playerList = new LinkedBlockingQueue<>();
//            for (int i = 0; i < 8; i++) {
//                Player poll = matchQueue.poll();
//                if (poll != null) {
//                    playerList.add(poll);
//                }
//            }
//            matchResult.setMatchPlays(playerList);
//            matchResult.setState(2);
//        }
//        matchResult.setMatchSize(matchQueue.size());
//        if(matchResult.getState() == 2){
//            matchResult.setMatchSize(8);
//        }
//        return matchResult;
//    }

//    @Override
//    public void run() {
//        MatchResult matchResult = match0();
//        if (matchResult != null && matchResult.getState() != 0) {
//            matchResults.add(matchResult);
//        }
//    }


    public static Map<Integer, Player> getPlayerMap() {
        return playerMap;
    }

    public static Queue<Player> getMatchQueue() {
        return matchQueue;
    }

    public static Queue<MatchResult> getMatchResults() {
        return matchResults;
    }

    public static MatchResult getFirstMatchResults() {
        return matchResults.poll();
    }

    public static void cancelMatch(int id) {
        matchQueue.remove(playerMap.get(id));
    }
}
